/**
 * @author        lx <1154354121@qq.com>
 * @date          2025-04-14 15:02:37
 * Copyright © YourCompanyName All rights reserved
 */
// app/api/auth/[...nextauth]/route.ts
import NextAuth from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';

export const authOptions = {
  providers: [
    CredentialsProvider({
      name: 'Credentials',
      credentials: {
        email: { label: '邮箱', type: 'email' },
        password: { label: '密码', type: 'password' },
      },
      async authorize(credentials) {
        if (!credentials?.email || !credentials?.password) {
          throw new Error('请输入邮箱和密码');
        }

        // 调用后端 API 验证
        const res = await fetch('http://localhost:3000/api/login', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            email: credentials.email,
            password: credentials.password,
          }),
        });

        const user = await res.json();

        if (res.ok && user) {
          // 返回用户信息
          return { id: user.id, name: user.name, email: user.email };
        } else {
          // 验证失败
          throw new Error(user.message || '登录失败');
        }
      },
    }),
  ],
  callbacks: {
    async session({ session, token }: any) {
      // 将用户 ID 添加到 session
      session.user.id = token.sub;
      return session;
    },
  },
  pages: {
    signIn: '/login', // 自定义登录页面
  },
  // 可选：调试模式
  debug: process.env.NODE_ENV === 'development',
};

const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };
